<script setup>
import { ref, computed, unref, inject, watchEffect, watch } from 'vue'
import $api from '@/server/api'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
const props = defineProps({
  visible: {
    //是否显示弹窗
    type: Boolean,
    default: false
  },
  headers: {
    type: Array,
    default: []
  },
  ruleConfiguration: {
    type: Array,
    default: []
  }
})

const excelHeaders = ref([])

const columns = computed(() => {
  return [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 70
    },
    {
      title: '表头名称',
      dataIndex: 'itemName',
      key: 'itemName',
      width: 300
    },
    {
      title: '公式',
      dataIndex: 'formula',
      key: 'formula'
    },
    {
      title: '字段类别',
      dataIndex: 'filedType',
      key: 'filedType',
      width: 100
    },
    {
      title: '值类型',
      dataIndex: 'valueType',
      key: 'valueType',
      width: 100
    }
  ]
})

const itemGroupName = ref(null)

const groupList = ref([])

const selectedRowKeys = ref([])

const selectedRowsInfo = ref([])

const checked = ref(false)

watch(
  () => props.headers,
  value => {
    groupList.value = props.ruleConfiguration
    itemGroupName.value = groupList.value[groupList.value.length - 1]?.itemGroupName
    selectedRowKeys.value = value.map((item, index) => (item.disabled ? `${index}-${item.itemName}` : null)).filter(item => item !== null)
    excelHeaders.value = value
  },
  {
    immediate: true
  }
)

const filedTypeMap = {
  system: '系统项',
  import: '导入项',
  calculate: '计算项'
}

const valueTypeMap = {
  string: '文本',
  int: '数值',
  date: '日期'
}

const emit = defineEmits(['update:visible', 'handOk', 'mergeHeaders'])

const btnLoading = ref(false)

const handOk = async () => {
  if (!itemGroupName.value) {
    message.warning('请选择分组')
    return
  }
  console.log('selectedRowsInfo', selectedRowsInfo.value)
  const insertSelectedRows = selectedRowsInfo.value.filter(item => item?.disabled === false)

  console.log('insertSelectedRows', insertSelectedRows)

  if (insertSelectedRows.length === 0) {
    message.warning('请选择需要新增表头')
    return
  }

  btnLoading.value = true
  try {
    emit('handOk', {
      //分组id
      itemGroupName: itemGroupName.value,
      //所有表头
      headers: excelHeaders.value,
      //所有表头的key
      selectedRowKeys: selectedRowKeys.value,
      //所有选择的表头
      selectedRows: selectedRowsInfo.value,
      //去除已经添加的表头
      insertSelectedRows
    })
    btnLoading.value = false
  } catch (err) {
    btnLoading.value = false
    throw new Error('导入匹配表头失败' + err)
  }
}

const cancel = () => {
  emit('update:visible', false)
}

const mergeHeaders = async () => {
  emit('mergeHeaders', checked.value)
}

const useSystemFormulasConfirm = record => {
  console.log('record', record)
  //clone一份 公式信息
  record.formulaHtmlClone = record.formulaHtml
  record.dataMessageClone = record.dataMessage

  //系统数据设置 导入表头信息
  record.dataMessage = record.systemInfo.dataMessage
  record.formulaHtml = record.systemInfo.formulaHtml
  record.filedType = record.systemInfo.filedType
  record.valueType = record.systemInfo.valueType

  console.log('excelHeaders', excelHeaders.value)
}

//取消使用系统公式
const useSystemFormulasCancel = record => {
  record.dataMessage = record.dataMessageClone
  record.formulaHtml = record.formulaHtmlClone
  console.log('excelHeaders', excelHeaders.value)
}

const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (newSelectedRowKeys, selectedRowsData) => {
    selectedRowKeys.value = newSelectedRowKeys
    selectedRowsInfo.value = selectedRowsData
  },
  getCheckboxProps: record => ({
    disabled: record.disabled,
    name: record.name
  })
}
</script>

<template>
  <a-modal :visible="visible" :maskClosable="false" :closable="false" :width="1200" :footer="null">
    <div class="title">
      <img src="@/assets/svg/scheme/success-icon.svg" alt="" />
      <div class="tip-text">已识别表头 {{ excelHeaders.length }} 项</div>
    </div>
    <div class="operate">
      <div class="operate-group">
        导入至分组：
        <a-select style="width: 120px" size="small" placeholder="请选择分组" v-model:value="itemGroupName">
          <a-select-option :value="item.itemGroupName" v-for="item in groupList">{{ item.itemGroupName }}</a-select-option>
        </a-select>
      </div>
      <a-checkbox v-model:checked="checked" @change="mergeHeaders" class="checkbox">
        <span class="text-color">将多行表头合并至一行</span>
      </a-checkbox>
    </div>

    <div class="tips-descript">
      <a-table
        :rowKey="(record, index) => index + '-' + record.itemName"
        :row-selection="rowSelection"
        bordered
        :columns="columns"
        :scroll="{ y: 500 }"
        :data-source="excelHeaders"
        :pagination="false"
      >
        <template #bodyCell="{ column, record, text, index }">
          <template v-if="column.dataIndex === 'index'">
            {{ index + 1 }}
          </template>

          <template v-if="column.dataIndex === 'formula'">
            <div class="formula-content">
              <span v-if="record.formulaHtml">
                <span v-html="record.formulaHtml"></span>
              </span>
              <span v-else style="color: rgba(0, 0, 0, 0.25)">无</span>

              <a-popconfirm placement="topLeft" ok-text="使用系统公式" cancel-text="取消" @cancel="useSystemFormulasCancel(record)" @confirm="useSystemFormulasConfirm(record)">
                <template #title>
                  <div>
                    <div class="detection-title">
                      检测到 「<span style="color: #5975fb"> {{ record.itemName }}」</span> 存在系统公式：
                    </div>
                    <div class="formulaHtml-content">
                      <span v-html="record.systemInfo.formulaHtml"></span>
                    </div>
                  </div>
                </template>
                <div v-if="record.systemInfo && record.systemInfo.formulaHtml" class="formula-operate">
                  <img class="detectionFormulas" src="@/assets/svg/scheme/gongshi-tips.svg" alt="" style="margin-left: 8px" />
                  <span>检测系统公式</span>
                </div>
              </a-popconfirm>
            </div>
          </template>

          <template v-if="column.dataIndex === 'filedType'">
            <span v-if="filedTypeMap[record.filedType]">{{ filedTypeMap[record.filedType] }}</span>
            <span v-else style="color: rgba(0, 0, 0, 0.25)">无</span>
          </template>

          <template v-if="column.dataIndex === 'valueType'">
            <span v-if="valueTypeMap[record.valueType]">{{ valueTypeMap[record.valueType] }}</span>
            <span v-else style="color: rgba(0, 0, 0, 0.25)">无</span>
          </template>
        </template>
      </a-table>
    </div>

    <div style="margin-top: 20px; text-align: right">
      <a-button @click="cancel" class="my-btn" :loading="btnLoading">取消</a-button>
      <a-button type="primary" @click="handOk" class="my-btn" :loading="btnLoading">确定</a-button>
    </div>
  </a-modal>
</template>

<style lang="less" scoped>
.title {
  display: flex;
  align-items: center;
  img {
    width: 20px;
  }
  .tip-text {
    font-size: 16px;
    font-weight: bold;
    margin-left: 10px;
    color: rgba(0, 0, 0, 0.85);
  }
}

.tips-descript {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.7);
  margin-top: 20px;
  line-height: 1.7;
  .checkbox {
    margin-top: 32px;
  }
}

.text-color {
  color: rgba(0, 0, 0, 0.85);
}
.operate {
  display: flex;
  margin-top: 20px;
  gap: 32px;
  .operate-group {
    display: flex;
    align-items: center;
    color: #5975fb;
    &:before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 16px;
      background-color: #5975fb;
      margin-right: 8px;
    }
  }
}
.formula-content {
  display: flex;
  align-items: center;
  cursor: pointer;
  .formula-operate {
    display: flex;
    align-items: center;
    margin-left: 24px;
    color: #ff7600;
    span {
      //不换行
      white-space: nowrap;
    }
    .detectionFormulas {
      width: 24px;
      cursor: pointer;
      margin-right: 6px;
    }
  }
}
.formulaHtml-content {
  max-width: 320px;
  margin: 12px 0;
}
.detection-title {
  font-weight: 550;
}
</style>

<style lang="less">
.my-btn {
  margin-left: 12px;
  &.ant-btn-primary[disabled] {
    background-color: rgba(89, 117, 251, 0.4) !important;
    border-color: rgba(0, 0, 0, 0) !important;
    color: rgba(255, 255, 255, 0.85);
  }
}
.filed-span {
  color: #5975fb;
}
</style>
